package com.ysg.widget.pic;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.interfaces.OnBitmapWatermarkEventListener;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.ysg.widget.pic.watermark.WatermarkEntity;
import com.ysg.widget.pic.watermark.WatermarkUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WatermarkEventListener implements OnBitmapWatermarkEventListener {
    private WatermarkEntity waterMaskBean;

    public WatermarkEventListener(WatermarkEntity waterMaskBean) {
        this.waterMaskBean = waterMaskBean;
    }

    @Override
    public void onAddBitmapWatermark(Context context, String srcPath, String mimeType, OnKeyValueResultCallbackListener call) {
        Glide.with(context).asBitmap().sizeMultiplier(0.6F).load(srcPath).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Bitmap watermarkBitmap = WatermarkUtil.getInstance().drawBitmap(context, waterMaskBean, resource);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                watermarkBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
                watermarkBitmap.recycle();
                FileOutputStream fos = null;
                String result = null;
                try {
                    File targetFile = new File(WatermarkUtil.DIR, DateUtils.getCreateFileName("Mark_") + ".jpg");
                    fos = new FileOutputStream(targetFile);
                    fos.write(stream.toByteArray());
                    fos.flush();
                    result = targetFile.getAbsolutePath();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    PictureFileUtils.close(fos);
                    PictureFileUtils.close(stream);
                }
                if (call != null) {
                    call.onCallback(srcPath, result);
                }
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
                if (call != null) {
                    call.onCallback(srcPath, "");
                }
            }
        });
    }
}
